package com.niuwa.p2p.interceptor;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.ehcache.Cache;

import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * @ClassName: MethodCacheAfterAdvice
 * @Description: 重载缓存
 * @author: zhangbo
 * @date:2015年1月13日 下午2:43:55
 */
public class MethodCacheAfterAdvice implements AfterReturningAdvice,
		InitializingBean {

	private static Logger logger = Logger
			.getLogger(MethodCacheAfterAdvice.class);

	@Autowired
	private Cache cache;

	@Value("#{propertiesReader['system.devMode']}")
	private boolean isDevMode;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (null == cache)
			throw new IllegalArgumentException("Cache should not be null.");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void afterReturning(Object returnValue, Method method,
			Object[] args, Object target) throws Throwable {
		if (!isDevMode) {
			logger.info("Remove cache start.");
			String className = target.getClass().getName();
			List<String> cacheKeys = cache.getKeys();
			for (String cacheKey : cacheKeys) {
				if (cacheKey.startsWith(className)) { // 清除缓存
					cacheKeys.remove(cacheKey);
				}
			}
		}
	}
}
